<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    用户名：<input type="text" id="username">
    <br>
    密码：<input type="text" id="password">
    <br>
    <button id="register">注册</button>
    <button id="login">登录</button>



    <script>
        let persons = [{
            "username": "xiaoming1",
            "password": "1111"
        }, {
            "username": "xiaoming2",
            "password": "222"
        }, {
            "username": "xiaoming3",
            "password": "33333"
        }];

        //获取元素
        let register = document.getElementById('register');
        let login = document.getElementById('login');
        let username = document.getElementById('username');
        let password = document.getElementById('password');
        let user = {};
        //注册
        register.onclick = function () {
            // 判空
            if (!username.value || !password.value) {
                alert('用户名或密码不能为空');
                return;
            }; 
            //把输入框的值加进user里
            user.username = username.value;
            user.password = password.value;
            //把数组里的值进行储存，如果一开始就没有，那就用persons，
            let p = localStorage.getItem("t") ? JSON.parse(localStorage.getItem("t")) : persons.some(val => {
                return val.username == user.username && val.password == user.password;
            });
            if (!p) {
                //添加
                persons.push(user);
                alert('注册成功');
                //储存,因为储存只能是字符串，所以转成字符串
                localStorage.setItem('t', JSON.stringify(persons));
                return;
            } else {
                alert('用户名已注册');
                username.value = '';
                password.value = '';
            };
        };

        //登录
        login.onclick = function () {
            // 判空
            if (!username.value || !password.value) {
                alert('用户名或密码不能为空');
                return;
            };
            //把输入框的值加进user里
            user.username = username.value;
            user.password = password.value;
            //提出储存的值是字符串无法判断，所以转成对象或数组形式进行判断
            let arr = JSON.parse(localStorage.getItem("t"));
            let lo = arr.some(val => {
                return val.username == user.username && val.password == user.password;

            });
            //判断
            if (lo) {
                alert('登录成功');
                username.value = '';
                password.value = '';
            } else {
                alert('未找到，请注册');
            };
        };
    </script>
</body>

</html>